<?php

namespace backend\controllers;

use Yii;
use backend\models\Contract;
use backend\models\ContractFile;
use backend\models\ContractSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use Da\User\Filter\AccessRuleFilter;
use yii\web\UploadedFile;
use yii\data\ActiveDataProvider;

/**
 * ContractController implements the CRUD actions for Contract model.
 */
class ContractController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'ruleConfig' => [
                    'class' => AccessRuleFilter::class,
                ],
                'rules' => [
                    [
                        'allow' => true,
                        'actions' => ['index', 'view', 'static-page'],
                        'roles' => ['browseContract'],
                    ],
                    [
                        'allow' => true,
                        'actions' => ['my-index'],
                        'roles' => ['browseMyContract'],
                    ],
                    [
                        'allow' => true,
                        'actions' => ['create', 'add-file'],
                        'roles' => ['createContract'],
                    ],
                    [
                        'allow' => true,
                        'actions' => ['update'],
                        'roles' => ['updateContract'],
                    ],
                    [
                        'allow' => true,
                        'actions' => ['delete', 'delete-file'],
                        'roles' => ['deleteContract'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Contract models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new ContractSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Lists all Contract models.
     * @return mixed
     */
    public function actionMyIndex()
    {
        $searchModel = new ContractSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $dataProvider->query->andWhere([ 'id_liable_user' => \Yii::$app->user->identity->id]);

        return $this->render('my-index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Contract model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        $model = $this->findModel($id);

        $filesDataProvider = new ActiveDataProvider([
            'query' => $model->getFiles(),
            'pagination' => false,
        ]);

        return $this->render('view', [
            'model' => $model,
            'filesDataProvider' => $filesDataProvider,
        ]);
    }

    public function actionStaticPage($page)
    {
        return $this->render($page);
    }

    /**
     * Creates a new Contract model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Contract();
        $model->registry_number = Contract::generateRegistryNumber();
        $model->is_yearly = Contract::ONE_TIME;

        if ($model->load(Yii::$app->request->post())) 
        {
            $model->docKpRequestOne = UploadedFile::getInstance($model, 'docKpRequestOne');
            $model->docKpRequestTwo = UploadedFile::getInstance($model, 'docKpRequestTwo'); 
            $model->docKpAnswerOne = UploadedFile::getInstance($model, 'docKpAnswerOne'); 
            $model->docKpAnswerTwo = UploadedFile::getInstance($model, 'docKpAnswerTwo');
            $model->docKpScreenshot = UploadedFile::getInstance($model, 'docKpScreenshot');
            $model->docMainContract = UploadedFile::getInstance($model, 'docMainContract');
            $model->docInvoice = UploadedFile::getInstance($model, 'docInvoice');
            $model->docClose = UploadedFile::getInstance($model, 'docClose');
            $model->docPaymentOrder = UploadedFile::getInstance($model, 'docPaymentOrder');

            if($model->validate())
            {
                if($model->save(false))
                {
                    return $this->redirect(['view', 'id' => $model->id]);
                }
            }
        }

        return $this->render('create', [
            'model' => $model,
        ]);
    }

    /**
     * Creates a new ContractFile model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionAddFile($id)
    {
        $contractModel = $this->findModel($id);

        $model = new ContractFile();
        $model->id_contract = $contractModel->id;
        $model->contractOwnNumber = $contractModel->own_number;
        $model->contractRegistryNumber = $contractModel->registry_number;

        $filesDataProvider = new ActiveDataProvider([
            'query' => $contractModel->getFiles(),
            'pagination' => false,
        ]);

        if ($model->load(Yii::$app->request->post())) 
        {
            $model->file = UploadedFile::getInstance($model, 'file');

            if($model->validate())
            {
                if($model->save(false))
                {
                    return $this->redirect(['add-file', 'id' => $contractModel->id]);
                }
            }
        }

        return $this->render('add-file', [
            'model' => $model,
            'contractModel' => $contractModel,
            'filesDataProvider' => $filesDataProvider,
        ]);
    }

    /**
     * Updates an existing Contract model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post())) 
        {

            $model->docKpRequestOne = UploadedFile::getInstance($model, 'docKpRequestOne');
            $model->docKpRequestTwo = UploadedFile::getInstance($model, 'docKpRequestTwo'); 
            $model->docKpAnswerOne = UploadedFile::getInstance($model, 'docKpAnswerOne'); 
            $model->docKpAnswerTwo = UploadedFile::getInstance($model, 'docKpAnswerTwo');
            $model->docKpScreenshot = UploadedFile::getInstance($model, 'docKpScreenshot');
            $model->docMainContract = UploadedFile::getInstance($model, 'docMainContract');
            $model->docInvoice = UploadedFile::getInstance($model, 'docInvoice');
            $model->docClose = UploadedFile::getInstance($model, 'docClose');
            $model->docPaymentOrder = UploadedFile::getInstance($model, 'docPaymentOrder');

            if($model->validate())
            {
                if($model->save(false))
                {
                    return $this->redirect(['view', 'id' => $model->id]);
                }
            }

        }

        return $this->render('update', [
            'model' => $model,
        ]);
    }

    /**
     * Deletes an existing Contract model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Deletes an existing ContractFile model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDeleteFile($id)
    {
        if (($model = ContractFile::findOne($id)) !== null) {
            $model->delete();
        }

        return $this->redirect(Yii::$app->request->referrer);
    }

    /**
     * Finds the Contract model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Contract the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Contract::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
}
